import mqtt from 'mqtt'
//初始化MQTT
const initMqtt = () => {
  let commonApi = 'http://192.168.1.39:8089'
  // var mqtt = require('mqtt')
  let options = {
    //mqtt客户端的id
    clientId: 'clientId-' + 123,
    username: 'admin',
    password: '12345',
  }
  this.client = mqtt.connect(commonApi, options)
  this.client.on('connect', () => {
    console.log('连接成功....')
  })
  //如果连接错误，打印错误
  this.client.on('error', (err) => {
    console.log('err=>', err)
    this.client.end()
  })
}

// 接收MQTT消息
const mqttReceive = () => {
  let topic = 'topic/response' //要接收的主题
  this.client.subscribe(topic, (err) => {
    if (!err) {
      console.log('subscribe success!')
    } else {
      //打印错误
      console.log('err', err)
    }
  })
  this.client.on('message', (topic, message) => {
    this.logs.push(message)
  })
}

export { initMqtt, mqttReceive }
